from __future__ import print_function
from flask import Flask, render_template, request
import json
import config
import ora_db3
app = Flask(__name__)
# app.config.from_object('imsi_wifi.config')
app.config.from_object('config')
# avoid conflict with angular js
app.config.from_envvar('FLASKR_SETTINGS', silent=True)
# app.config.update(config)
app.jinja_env.variable_start_string = '{['
app.jinja_env.variable_end_string = ']}'

#
# @app.route('/hello')
# def hello_world():
#     return "hello world"


@app.route('/', methods=['GET', 'POST'])
def main():
    return render_template('index.html')


# return json array
@app.route('/api/select_by_imsi', methods=['POST'])
def select_by_imsi():
    imsi = request.json.get('imsi')
    result = ora_db3.select_by_imsi(imsi)
    sorted_result = sorted(result, key=lambda item: item[2], reverse=True)
    return json.dumps(sorted_result)


# return json array
@app.route('/api/select_by_mac', methods=['POST'])
def select_by_mac():
    mac = request.json.get('mac')
    result = ora_db3.select_by_mac(mac)
    sorted_result = sorted(result, key=lambda item: item[2], reverse=True)
    return json.dumps(sorted_result)


# return json array
@app.route('/api/find_by_imsi', methods=['POST'])
def find_by_imsi():
    imsi = request.json.get('imsi')
    result = ora_db3.find_mac_by_imsi_with_freq_threshold(imsi)
    sorted_result = sorted(result, key=lambda item: item[2], reverse=True)
    return json.dumps(sorted_result)


# return json array
@app.route('/api/find_by_mac', methods=['POST'])
def find_by_mac():
    mac = request.json.get('mac')
    result = ora_db3.find_imsi_by_mac_with_freq_threshold(mac)
    sorted_result = sorted(result, key=lambda item: item[2], reverse=True)
    return json.dumps(sorted_result)


if __name__ == '__main__':
    app.run(port=config.user_defined_port)
